package org.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @author PengGuangZao
 */
public class SqlSessionFactoryUtils {
    private static SqlSessionFactory sqlSessionFactory = null;

    /**
     * 初始化创建SqlSessionFactory对象
     */
    static{
        // 读取mybatis-config.xml文件
        try (InputStream is = Resources.getResourceAsStream("mybatis/mybatis-config.xml")){
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取SqlSession对象的静态方法
     * @return
     */
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

    /**
     * 获取SqlSessionFactory的静态方法
     * @return
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}
